import { Component, Inject, OnInit } from '@angular/core';
import { NzMessageService, NzUploadFile } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { CustomService } from 'src/app/service/custom.service';
import { OprationService } from 'src/app/service/opration.service';
import { API_CONFIG } from 'src/app/service/service.module';

@Component({
  selector: 'app-real-auth',
  templateUrl: './real-auth.component.html',
  styleUrls: ['./real-auth.component.less']
})
export class RealAuthComponent implements OnInit {

  data: any = { userType: 1 };
  card: any = {
    url1: '/assets/images/sample1.jpg',
    url2: '/assets/images/sample2.jpg',
    url3: '/assets/images/sample3.jpg'
  }
  loading = false;
  avatarUrl?: string;
  uploadUrl: string | null = '';
  headers: any | null = null;
  previewImage: string | undefined = '';
  previewVisible: boolean = false;

  handlePreview = async (file: NzUploadFile) => {

    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };

  userTypeChange(tp: number) {
    this.customService.modify({ userType: tp }).subscribe(result => { });
  }

  submitAuth() {
    this.customService.modify({ authentication: 1 }).subscribe(result => {
      this.data['authentication'] = 1;
      this.msg.success('提交认证成功');
    });
  }

  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]) => {
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.msg.error('必须上传一张图片!');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.msg.error('图片不能大于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  };

  handleChange(info: { file: NzUploadFile }, tp: number): void {
    switch (info.file.status) {
      case 'uploading':
        this.loading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        if (this.data['authentication'] !== 1) {
          this.card['url' + tp.toString()] = info.file.response.url;
          let card = {};
          if (this.data['cardImages'] && this.data['cardImages'] !== '')
            card = JSON.parse(this.data['cardImages']);
          card['url' + tp.toString()] = info.file.response.name;
          let data = { "cardImages": JSON.stringify(card) };
          data['userType'] = this.data['userType'];
          this.data['cardImages'] = data['cardImages'];
          this.customService.modify(data).subscribe(result => {
            this.msg.success('证件上传成功');
          });
        }
        else {
          this.msg.success('您已经认证成功');
        }
        this.loading = false;
        break;
      case 'error':
        this.msg.error('Network error');
        this.loading = false;
        break;
    }
  }

  constructor(
    private customService: CustomService,
    private msg: NzMessageService,
    private oprationService: OprationService,
    @Inject(API_CONFIG) private uri: string
  ) { }

  ngOnInit(): void {
    this.uploadUrl = this.uri + '/custom/upload/authentication';
    let ticket = window.sessionStorage['ticket'];
    this.headers = { 'Authorization': 'BasicAuth ' + ticket };
    this.customService.profile().subscribe(result => {
      this.data = result['data'];
      if (this.data['cardImages'] && this.data['cardImages'] !== '') {
        let card: any = JSON.parse(this.data['cardImages']);
        let uri = this.oprationService.ossUri;
        if (card['url1'])
          this.card['url1'] = uri + card['url1'];
        if (card['url2'])
          this.card['url2'] = uri + card['url2'];
        if (card['url3'])
          this.card['url3'] = uri + card['url3'];
      }
      this.data['userType'] = this.data['userType'] === 0 ? 1 : this.data['userType'];
    });
  }

}
